package com.cyq.order.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Aspect
@Component
public class MethodCallCounterAspect {

    private Map<String, AtomicInteger> methodCallCountMap = new ConcurrentHashMap<>();

    @Around("@annotation(com.cyq.order.aop.MethodCallCount)")
    public Object facade(ProceedingJoinPoint pjp) {

        Method method = ((MethodSignature) pjp.getSignature()).getMethod();
        String methodName = method.getName();

        try {
            return pjp.proceed();
        } catch (Throwable e) {
            // 异常处理
            throw new RuntimeException(e);
        } finally {
            // 计数+1
            AtomicInteger atomicInteger = methodCallCountMap.computeIfAbsent(methodName, k -> new AtomicInteger(0));
            atomicInteger.incrementAndGet();
        }
    }

    public int getMethodCallCount(String methodName) {
        AtomicInteger counter = methodCallCountMap.get(methodName);
        return counter != null ? counter.get() : 0;
    }
}